package com.moment.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;

import com.moment.model.GlobalClass;
import com.moment.model.ProfileDetailsData;
import com.moment.model.UserReg;
import com.moment.model.WalletData;
import com.moment.util.Converter;
import com.moment.util.Geocoding;
import com.moment.webservice.Services;
import com.moment.webservice.ServicesProxy;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

/**
 * Servlet implementation class ProfileController
 */
@WebServlet("/ProfileController")
public class ProfileController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ProfileController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doCall(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doCall(request, response);
	}

	protected void doCall(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String updateorsave = request.getParameter("updateorsave");
		System.out.println("updateorsave" + updateorsave);
		if (updateorsave == null) {// call update method

			HttpSession session = request.getSession();
			try {
				List<FileItem> items = new ServletFileUpload(
						new DiskFileItemFactory()).parseRequest(request);
				String dlimit = null;
				String mlimit = null;
				String address = null;
				String geolimit = null;
				String base64String = null;
				for (FileItem item : items) {
					if (item.isFormField()) {
						// Process regular form field (input
						// type="text|radio|checkbox|etc", select, etc).
						String fieldname = item.getFieldName();
						String fieldvalue = item.getString();
						System.out.println(fieldname + ":" + fieldvalue);
						if (fieldname.equals("dlimit")) {
							dlimit = fieldvalue;
						} else if (fieldname.equals("mlimit")) {
							mlimit = fieldvalue;
						} else if (fieldname.equals("address")) {
							address = fieldvalue;

						} else if (fieldname.equals("geolimit")) {
							geolimit = fieldvalue;
						}
					} else {
						System.out.println("item .getCotenttype:"
								+ item.getContentType());
						String[] typeOfImage = item.getContentType().split("/");
						if (typeOfImage[1].equalsIgnoreCase("jpeg")
								|| typeOfImage[1].equalsIgnoreCase("png")
								|| typeOfImage[1].equalsIgnoreCase("jpg")) {
							base64String = Base64.encode(item.get());
							System.out.println("Base 64 string of Img:"
									+ base64String);

						} else {
							session.setAttribute("error", "Profile image error");
							response.sendRedirect("jsp/profile.jsp");
						}

					}

				}

				String s[] = null;
				try {
					s = new Geocoding().GetLatlong(address).split(",");
					for (String ss : s) {

						System.out.println("ss=" + ss);
					}
				} catch (XPathExpressionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// --New CODE-------------
				Map<String, String> map = new HashMap<String, String>();
				map.put("method", "21");
				map.put("mnum", (String) session.getAttribute("username"));
				map.put("dlimit", dlimit);
				map.put("mlimit", mlimit);
				map.put("address", address);
				map.put("geolimit", geolimit);
				map.put("lat", s[0]);
				map.put("longi", s[1]);
				map.put("img", base64String);

				String json = new Converter().mapToJson(map);
				System.out.println("json String :" + json);
				Services serviceproxy = new ServicesProxy();

				String output = serviceproxy.service(json);
				// ---------------------------
				// String
				// output=proxy.updateProfile((String)session.getAttribute("username"),
				// dlimit, mlimit, address, geolimit, s[0], s[1],
				// userObj.getImagestr()) ;
				if (output.equalsIgnoreCase("Success")) {
					session.setAttribute("success", "Profile updated");

					UserReg userObj = (UserReg) session.getAttribute("userObj");
					userObj.setImagestr(base64String);
					session.setAttribute("userObj", userObj);
					response.sendRedirect("jsp/viewprofile.jsp");
				} else {
					session.setAttribute("error", "Profile not updated");
					response.sendRedirect("jsp/profile.jsp");

				}

			} catch (FileUploadException e) {
				throw new ServletException("Cannot parse multipart request.", e);
			}

			// ----------old code -----------------------
			/*
			 * String dlimit=request.getParameter("dlimit"); String
			 * mlimit=request.getParameter("mlimit"); String
			 * address=request.getParameter("address"); String
			 * geolimit=request.getParameter("geolimit"); UserReg
			 * userObj=(UserReg)session.getAttribute("userObj");
			 * 
			 * System.out.println(" "+dlimit+" "+mlimit+" "+address);
			 */
			/*
			 * String s[]=null; try { s = new
			 * Geocoding().GetLatlong(address).split(","); for(String ss:s){
			 * 
			 * 
			 * System.out.println("ss="+ss); } } catch (XPathExpressionException
			 * e) { // TODO Auto-generated catch block e.printStackTrace(); }
			 * catch (ParserConfigurationException e) { // TODO Auto-generated
			 * catch block e.printStackTrace(); } catch (SAXException e) { //
			 * TODO Auto-generated catch block e.printStackTrace(); } //--New
			 * CODE------------- Map<String,String> map=new
			 * HashMap<String,String>(); map.put("method", "21");
			 * map.put("mnum",(String)session.getAttribute("username"));
			 * map.put("dlimit",dlimit); map.put("mlimit",mlimit);
			 * map.put("address",address); map.put("geolimit",geolimit);
			 * map.put("lat",s[0]); map.put("longi",s[1]);
			 * map.put("img",userObj.getImagestr());
			 * 
			 * String json=new Converter().mapToJson(map);
			 * System.out.println("json String :"+json); Services
			 * serviceproxy=new ServicesProxy();
			 * 
			 * String output=serviceproxy.service(json);
			 * //--------------------------- //String
			 * output=proxy.updateProfile(
			 * (String)session.getAttribute("username"), dlimit, mlimit,
			 * address, geolimit, s[0], s[1], userObj.getImagestr()) ;
			 * if(output.equalsIgnoreCase("Success")){
			 * session.setAttribute("success", "Profile updated");
			 * response.sendRedirect("jsp/profile.jsp"); }else{
			 * session.setAttribute("error", "Profile not updated");
			 * response.sendRedirect("jsp/profile.jsp");
			 * 
			 * }
			 */
		} else if (updateorsave.equalsIgnoreCase("view")) {// view all data
			System.out.println("in the else part");
			HttpSession session = request.getSession();
			UserReg userObj = (UserReg) session.getAttribute("userObj");
			WalletData walletObj = (WalletData) session
					.getAttribute("walletObj");
			ProfileDetailsData profileObj = new ProfileDetailsData();

			// --New CODE-------------
			Map<String, String> map = new HashMap<String, String>();
			map.put("method", "20");
			map.put("mnum", (String) session.getAttribute("username"));

			String json = new Converter().mapToJson(map);
			System.out.println("json String :" + json);
			Services serviceproxy = new ServicesProxy();

			String ss = serviceproxy.service(json);
			// ---------------------------
			// WebsProxy proxy=new WebsProxy();
			// String
			// ss=proxy.getProfile((String)session.getAttribute("username"));
			System.out.println("output from the webService " + ss);
			JSONArray jArray;
			JSONObject jobj = null;
			try {
				jArray = new JSONArray(ss);
				jobj = jArray.getJSONObject(0);
				userObj.setName(jobj.getString("name"));
				if (jobj.isNull("addr")) {
					profileObj.setAddr("");
				} else {
					profileObj.setAddr(jobj.getString("addr"));

				}
				// profileObj.setAddr(jobj.getString("addr"));
				profileObj.setGeolimit(jobj.getString("geolimit"));
				walletObj.setWdlimit(jobj.getString("dlimit"));
				walletObj.setWmlimit(jobj.getString("mlimit"));
				System.out.println("userObj name" + userObj.getName());
				System.out.println("profileObj name" + profileObj.getAddr());
				System.out
						.println("profileObj name" + profileObj.getGeolimit());
				System.out.println("walletObj name" + walletObj.getWdlimit());
				System.out.println("walletObj name" + walletObj.getWmlimit());

				session.setAttribute("userObj", userObj);
				session.setAttribute("profileObj", profileObj);
				session.setAttribute("walletObj", walletObj);
				response.sendRedirect("jsp/profile.jsp");

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (updateorsave.equalsIgnoreCase("save")) {// call saving

		} else {

		}

	}

}
